/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;


/**
 * @author Joe Grandja
 * modifer by hcj
 */
@Slf4j
@Controller
public class AuthorizationForWebFluxController {

    @Value("${messages.base-uri}")
    private String messagesBaseUri;
    @Value("${messages.openIdUri:http://localhost:8082/openid}")
    private String openIdUri;
//    @Value("${messages.openIdUriwithshowservice:http://localhost:8082/openid}")
//    private String openIdUri;

    @Autowired
    private WebClient webClient;

    @GetMapping(value = "/authorizeforOpenidWithloadbalance", params = "grant_type=authorization_code")
    public String authorization_code_grant_oidc_loadbalance(Model model) {
        log.info("grant_type=authorization_code");
        Mono<String[]> mono = retrieveOpenIdMessage("messaging-client-oidc");
        model.addAttribute("messages", mono);
        return "index";
    }

    // messaging-client-oidc
//    @GetMapping(value = "/authorizeforOpenidWithshowservice", params = "grant_type=authorization_code")
//    public String authorization_code_grant_oidc_showService(Model model) {
//        log.info("grant_type=authorization_code");
//        Mono<String[]> mono = retrieveOpenIdMessage("messaging-client-oidc");
//        model.addAttribute("messages", mono);
//        return "index";
//    }

//    @GetMapping(value = "/authorize", params = "grant_type=authorization_code")
//    public String authorization_code_grant(Model model) {
//        log.info("grant_type=authorization_code");
//        Mono<String[]> mono = retrieveMessages("messaging-client-authorization-code");
//        model.addAttribute("messages", mono.block());
//        return "index";
//    }

//	@GetMapping(value = "/authorized", params = OAuth2ParameterNames.ERROR)
//	public String authorizationFailed(Model model, WebRequest request) {
//		String errorCode = request.getParameter(OAuth2ParameterNames.ERROR);
//		if (StringUtils.hasText(errorCode)) {
//			model.addAttribute("error",
//					new OAuth2Error(
//							errorCode,
//							request.getParameter(OAuth2ParameterNames.ERROR_DESCRIPTION),
//							request.getParameter(OAuth2ParameterNames.ERROR_URI))
//			);
//		}
//		return "index";
//	}


    private Mono<String[]> retrieveMessages(String clientRegistrationId) {
        return this.webClient
                .get()
                .uri(this.messagesBaseUri)
                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistrationId))
                .retrieve()
                .bodyToMono(String[].class);
    }

    private Mono<String[]> retrieveOpenIdMessage(String clientRegistrationId) {
        return this.webClient
                .get()
                .uri(this.openIdUri)
                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistrationId))
                .retrieve()
                .bodyToMono(String[].class);
    }
}